package FenxiaoService

import (
	"context"
	"errors"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/entity"
	"gdshop-back-end-go/common/tools/mylog"
	"gdshop-back-end-go/service-order/FenxiaoBaseService"
	"github.com/gogf/gf/errors/gerror"
	"time"
)

// GetMemberLevel 获取用户等级
func GetMemberLevel(ctx context.Context, memberId int) (*entity.FenxiaoLevel, error) {
	fuModel, err := FenxiaoBaseService.GetFenxiaoUserModelByMemberId(ctx, memberId)
	if err != nil {
		if gerror.Code(err) != 6000 {
			mylog.ErrorLog("GetMemberLevel GetFenxiaoUserModelByMemberId " + err.Error())
			return nil, err
		}
		return nil, err
	}
	if fuModel == nil {
		// 不代表是错误，有可能当前用户不是分销商
		return nil, gerror.NewCode(6001, "没有找到数据")
	}

	if fuModel.Status == 0 {
		// 用户 被禁用
		return nil, gerror.NewCode(6002, "分销商被禁用")
	}
	var flModel *entity.FenxiaoLevel
	err = toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "fenxiao_level").Cache(600*time.Second).Where("id", fuModel.LevelId).Scan(&flModel)
	if err != nil {
		mylog.ErrorLog("GetMemberRate fenxiao_level " + err.Error())
		return nil, err
	}

	if flModel == nil {
		// 等级找不到，应该报错
		return nil, errors.New("fenxiao_level 找不到数据")
	}

	return flModel, nil
}
